package cn.tedu.medicalmanagementsystem.escort.controller;

import cn.tedu.medicalmanagementsystem.base.constant.EscortAuditStatus;
import cn.tedu.medicalmanagementsystem.base.file.FileUploadController;
import cn.tedu.medicalmanagementsystem.base.response.JsonResult;
import cn.tedu.medicalmanagementsystem.base.response.StatusCode;
import cn.tedu.medicalmanagementsystem.base.utils.JwtUtils;
import cn.tedu.medicalmanagementsystem.base.utils.UserContext;
import cn.tedu.medicalmanagementsystem.escort.mapper.EscortAppointmentMapper;
import cn.tedu.medicalmanagementsystem.escort.mapper.EscortMapper;
import cn.tedu.medicalmanagementsystem.escort.pojo.dto.*;
import cn.tedu.medicalmanagementsystem.escort.mapper.ServiceTrackMapper;
import cn.tedu.medicalmanagementsystem.escort.pojo.entity.Escort;
import cn.tedu.medicalmanagementsystem.escort.pojo.entity.EscortAppointment;
import cn.tedu.medicalmanagementsystem.escort.pojo.entity.ServiceStatus;
import cn.tedu.medicalmanagementsystem.escort.pojo.entity.ServiceTrack;
import cn.tedu.medicalmanagementsystem.escort.pojo.vo.EscortVO;
import cn.tedu.medicalmanagementsystem.escort.pojo.vo.ServiceTracksVO;
import cn.tedu.medicalmanagementsystem.escort.service.ReviewApplyService;
import cn.tedu.medicalmanagementsystem.manager.pojo.entity.Appointment;
import cn.tedu.medicalmanagementsystem.manager.pojo.vo.ServiceTrackVO;
import cn.tedu.medicalmanagementsystem.user.pojo.vo.ReviewVO;
import cn.tedu.medicalmanagementsystem.user.service.AppointmentService;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Value;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import javax.validation.Path;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.util.*;

@Slf4j
@RestController
@Api(tags = "陪诊员模块")
@RequestMapping("/v1/escort/")

public class EscortController {

    public static Long userIdd;

    @Autowired
    private EscortMapper escortMapper;
    @Autowired
    private ServiceTrackMapper serviceTrackMapper;
    @Autowired
    private ReviewApplyService reviewApplyService;

    /**
     * 1.陪诊员注册功能
     */
    @PostMapping("/register")
    @ApiOperation("陪诊员注册功能")
    @ApiOperationSupport(order = 10)
    public JsonResult reg(@Validated @RequestBody EscortRegParam escortRegParam) {
        log.debug("开始注册陪诊员，请求参数: {}", escortRegParam);

        String phone = escortRegParam.getPhone();
        if (escortMapper.existsByPhone(phone) > 0) {
            return new JsonResult(StatusCode.USERNAME_EXISTS);
        }

        // 映射并保存数据
        Escort escort = new Escort();
        BeanUtils.copyProperties(escortRegParam, escort);

        // ✅ 打印日志调试
        log.debug("映射后的 escort: {}", escort);

        // ✅ 手动检查并设置 realName（临时解决方案）
        if (escort.getRealName() == null || escort.getRealName().isEmpty()) {
            escort.setRealName(escortRegParam.getRealName());
        }

        // 设置创建时间
        escort.setCreateTime(new Date());

        // 设置初始审核状态为 pending
        escort.setStatus(EscortAuditStatus.AUDIT_STATUS_PENDING_STR);// "pending"

        // 设置默认值
        escort.setServiceCount(0); // 服务次数初始为0
        escort.setAvgRating(new BigDecimal("4.5")); // 平均评分初始为4.5
        escort.setStatus("pending"); // 审核状态初始为"pending"
        escort.setAuditComment("待审核");// 审核意见初始为"待审核"

//        // 手动检查并转换性别字段
//        String gender = escortRegParam.getGender();
//        if ("男".equals(gender)) {
//            escort.setGender("male");
//        } else if ("女".equals(gender)) {
//            escort.setGender("female");
//        } else {
//            escort.setGender("male"); // 默认值
//        }

        log.debug("准备插入陪诊员信息: {}", escort);
        escortMapper.insert(escort);
        return JsonResult.ok("注册成功，请等待管理员审核");
    }


    /**
     * 2.陪诊员登录功能
     */
    @PostMapping("/login")
    @ApiOperation("陪诊员登录功能")
    @ApiOperationSupport(order = 20)
    public JsonResult login(@RequestBody EscortLoginParam loginParam, @ApiIgnore HttpSession session) {
        log.debug("登录请求参数: {}", loginParam);

        // 1. 查询用户信息
        EscortVO escortVO = escortMapper.selectByPhone(loginParam.getPhone());
        if (escortVO == null) {
            log.warn("未找到手机号对应的陪诊员：{}", loginParam.getPhone());
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        }

        // ✅ 明文比对密码
        if (!loginParam.getPassword().equals(escortVO.getPassword())) {
            log.warn("密码错误，手机号：{}", loginParam.getPhone());
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        }

        // 3. 检查审核状态
        if (!"approved".equalsIgnoreCase(escortVO.getStatus())) {
            log.info("账号未通过审核，手机号：{}", loginParam.getPhone());
            return new JsonResult(StatusCode.ACCOUNT_NOT_APPROVED);
        }
        //  4. 登录成功，返回jwt令牌
        Map<String, Object> claims = new HashMap<>();
        log.info("escortId: {}", escortVO.getId());
        claims.put("escortId", escortVO.getId());
        userIdd = escortVO.getId();
        String jwt = JwtUtils.createJWT(
                "medical-management-system",
                1000 * 60 * 60 * 24 * 7L,
                claims
        );
        log.info("jwt: {}", jwt);
       /* // 4. 登录成功，存入 Session
        session.setAttribute("escort", escortVO);
        session.setAttribute("escortId", escortVO.getId());
*/
        //  5. 登录成功，返回登录信息
        escortVO.setToken(jwt);
        return JsonResult.ok(escortVO);
    }

    /*
     * 3.获取当前登录的陪诊员个人信息功能
     */
    @GetMapping("/info")
    @ApiOperation("获取当前登录的陪诊员个人信息功能")
    @ApiOperationSupport(order = 30)
    public JsonResult<EscortVO> getEscortInfo() {
       // 从 Session 中获取当前登录的陪诊员ID
        Long escortId = UserContext.getCurrentUser();
        log.debug("当前登录的陪诊员ID: {}", escortId);
        if (escortId == null) {
            return JsonResult.error("未登录或登录已过期");
        }

        // 根据ID查询陪诊员信息
        EscortVO escortInfo = escortMapper.selectById(Long.valueOf(escortId));
        if (escortInfo == null) {
            return JsonResult.error("未找到陪诊员信息");
        }

        return JsonResult.ok(escortInfo);
    }


    /**
     * 4.陪诊员查看预约自己的用户信息
     */
    @Autowired
    private EscortAppointmentMapper escortAppointmentMapper;

    @GetMapping("/appointments")
    @ApiOperation("陪诊员查看预约自己的用户信息")
    public JsonResult<Object> getAppointmentsByEscort(@ApiIgnore HttpSession session) {
        log.debug("进入陪诊员查看预约自己的用户信息接口");

        Long escortId = UserContext.getCurrentUser();
        if (escortId == null) {
            log.warn("陪诊员 ID 为空");
            return JsonResult.error("未登录或登录已过期");
        }

        List<EscortAppointment> appointments = escortAppointmentMapper.findAppointmentsByEscortId(escortId);
        log.debug("查询到 {} 条预约记录", appointments.size());

        // 确保 appointments 不为 null 并正确转换为 JSON 格式返回
         return JsonResult.ok(appointments);
    }



    /* 5.查看并修改服务跟踪状态和备注*/
    @GetMapping("/service-track")
    @ApiOperation("陪诊员查看自己的所有服务跟踪记录")
    public JsonResult<List<ServiceTracksVO>> getServiceTracks() {
        Long escortId = UserContext.getCurrentUser();
        if (escortId == null) {
            return JsonResult.fail(StatusCode.NOT_LOGIN, "请先登录");
        }
        List<ServiceTracksVO> tracks = serviceTrackMapper.selectByEscortId(escortId);
        log.info("查询到的服务跟踪记录: {}", tracks);
        return JsonResult.ok(tracks);
    }

    @PutMapping("/status-update")
    @ApiOperation("修改服务跟踪状态和备注")
    public JsonResult<Void> updateServiceTrackStatus(
            @RequestBody UpdateServiceTrackParam updateParam) {

        log.debug("开始修改服务跟踪状态，请求参数: {}", updateParam);

        // 检查参数有效性
        if (updateParam.getId() == null) {
            return JsonResult.fail(StatusCode.PARAMETER_ERROR, "ID不能为空");
        }
        if (!ServiceStatus.isValid(updateParam.getStatus())) {
            return JsonResult.fail("无效的状态值");
        }


        // 构建更新对象
        ServiceTrack updateTrack = new ServiceTrack();
        updateTrack.setId(updateParam.getId());
        updateTrack.setStatus(updateParam.getStatus());
        updateTrack.setRemark(updateParam.getRemark());

        // 执行更新
        int num = serviceTrackMapper.updateStatusAndRemark(updateTrack);
        if (num == 0) {
            return JsonResult.fail(StatusCode.SERVICE_NOT_FOUND, "未找到对应的服务记录");
        }
        return JsonResult.ok("服务状态更新成功");
    }

    /*
     * 6.陪诊员修改自己的个人信息功能（可修改个人简介，密码）
     */

    @PutMapping("/update")
    @ApiOperation("陪诊员修改自己的个人信息（个人简介、密码）")
    @ApiOperationSupport(order = 50)
    public JsonResult updateProfileOrPassword(@RequestBody @Validated EscortUpdate dto,
                                              @ApiIgnore HttpSession session) {
        // 1. 获取当前登录陪诊员
        Long escortId = UserContext.getCurrentUser();
        if (escortId == null) {
            return new JsonResult(StatusCode.NOT_LOGIN);
        }

        // 2. 查询数据库中的陪诊员实体
        EscortVO escort = escortMapper.selectById(escortId);
        if (escort == null) {
            return new JsonResult(StatusCode.USER_NOT_EXISTS);
        }

        // 3. 修改简介（如果提供了）
        if (dto.getProfile() != null) {
            escort.setProfile(dto.getProfile());
        }

        // 4. 修改密码（仅当 oldPassword 和 newPassword 都提供时）
        if (dto.getOldPassword() != null && dto.getNewPassword() != null) {
            // 验证旧密码是否正确
            if (!Objects.equals(escort.getPassword(), dto.getOldPassword())) {
                return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
            }
            // 设置新密码
            escort.setPassword(dto.getNewPassword());
        }

        // 5. 更新数据库
        escortMapper.updateById(escort);

        // 6. 返回成功结果
        return JsonResult.ok("资料更新成功", (List<EscortAppointment>) escort);
    }


    @GetMapping("/escort-reviews")
    @ApiOperation("陪诊员获取自己的所有评价")
    @ApiOperationSupport(order = 70)
    public JsonResult<List<ReviewVO>> getEscortReviews(
            @ApiIgnore HttpSession session) {

        Long escortId = UserContext.getCurrentUser();
        if (escortId == null) {
            return JsonResult.fail(StatusCode.NOT_LOGIN, "请先登录");
        }

        List<ReviewVO> reviews = reviewApplyService.getReviewsByEscort(escortId);
        return JsonResult.ok(reviews);
    }


    @PutMapping("/reply")
    @ApiOperation("陪诊员回复评价")
    @ApiOperationSupport(order = 80)
    public JsonResult<Void> replyReview(
            @RequestBody @Valid ReviewReplyParam param,
            @ApiIgnore HttpSession session) {

        Long escortId = UserContext.getCurrentUser();
        if (escortId == null) {
            return JsonResult.fail(StatusCode.NOT_LOGIN, "请先登录");
        }

        reviewApplyService.replyReview(param, escortId);
        return JsonResult.ok("回复成功");
    }

    /*
     * 陪诊员更新预约状态
     */
    @PutMapping("/status")
    @ApiOperation("陪诊员更新预约状态")
    @ApiOperationSupport(order = 90)
    public JsonResult updateAppointmentStatus(
            @RequestBody @Valid UpdateAppointmentStatusParam param) {

        Long escortId = UserContext.getCurrentUser();
        if (escortId == null) {
            return JsonResult.error("未登录或登录已过期");
        }
        // 查询当前预约是否属于该陪诊员
        List<EscortAppointment> appointments = escortAppointmentMapper.findAppointmentsByEscortId(escortId);
        // 检查预约是否存在
        boolean exists = appointments.stream()
                .anyMatch(app -> app.getId().equals(param.getId()));
        if (!exists) {
            return JsonResult.error("无权操作此预约");
        }
        // 更新状态
        escortAppointmentMapper.updateStatusById(param.getId(), param.getStatus());

        return JsonResult.ok("状态更新成功");
    }

   /* @GetMapping("/appointments/{id}")
    public JsonResult<EscortAppointment> getAppointmentById(@PathVariable Long id) {
        log.debug("根据ID获取预约详情，参数: id={}", id);
        Long escortId = UserContext.getCurrentUser();
        if (escortId == null) {
            return JsonResult.fail(StatusCode.NOT_LOGIN, "请先登录");
        }
        try {
            EscortAppointment appointment = escortAppointmentMapper.selectById(id);
            if (appointment == null) {
                return JsonResult.fail("预约不存在");
            }

            if (!appointment.getEscortId().equals(escortId)) {
                return JsonResult.fail(403, "无权访问此预约");
            }

            log.debug("查询到的预约详情: {}", appointment);
            return JsonResult.ok(appointment);
        } catch (Exception e) {
            log.error("获取预约详情时发生未知异常: ", e);
            return JsonResult.fail("未知异常");
        }
    }
*/
   @GetMapping("/appointments/{id}")
   public JsonResult<Map<String, Object>> getAppointmentById(@PathVariable Long id) {
       log.debug("根据ID获取预约详情，参数: id={}", id);
       Long escortId = UserContext.getCurrentUser();
       if (escortId == null) {
           return JsonResult.fail(StatusCode.NOT_LOGIN, "请先登录");
       }
       try {
           // 获取预约实体
           EscortAppointment appointment = escortAppointmentMapper.selectById(id);
           if (appointment == null) {
               return JsonResult.fail("预约不存在");
           }

           if (!appointment.getEscortId().equals(escortId)) {
               return JsonResult.fail(403, "无权访问此预约");
           }

           // 获取关联用户信息
           String contactName = appointment.getContactName();
           String contactPhone = appointment.getContactPhone();

           // 获取服务类型名称
           String serviceTypeName = escortAppointmentMapper.getServiceTypeNameById(appointment.getServiceTypeId());

           // 获取用户真实姓名
           String userName = escortAppointmentMapper.getUserNameById(appointment.getUserId());

           // 构造返回对象
           Map<String, Object> result = new HashMap<>();
           result.put("id", appointment.getId());
           result.put("userId", appointment.getUserId());
           result.put("userName", userName); // 新增用户名
           result.put("contactName", contactName);
           result.put("contactPhone", contactPhone);
           result.put("serviceTypeName", serviceTypeName);
           result.put("appointmentTime", appointment.getAppointmentTime());
           result.put("status", appointment.getStatus());
           result.put("paymentStatus", appointment.getPaymentStatus());
           result.put("totalAmount", appointment.getTotalAmount());
           result.put("createTime", appointment.getCreateTime());

           return JsonResult.ok(result);
       } catch (Exception e) {
           log.error("获取预约详情失败", e);
           return JsonResult.fail("未知错误");
       }
   }



    @GetMapping("/appointmentdetail")
    @ApiOperation("根据日期获取预约信息")
    public JsonResult<List<EscortAppointment>> getAppointmentDetailByDate(
            @RequestParam String date) {
        log.debug("根据日期获取预约数据，参数: date={}", date);

        Long escortId = UserContext.getCurrentUser();
        if (escortId == null) {
            return JsonResult.fail(StatusCode.NOT_LOGIN, "请先登录");
        }

        List<EscortAppointment> appointments = escortAppointmentMapper.findAppointmentsByEscortIdAndDate(escortId, LocalDate.parse(date));
        log.debug("查询到的预约数据: {}", appointments);
        return JsonResult.ok(appointments);
    }







}



